package com.yifushidai.service;

import com.alibaba.fastjson.JSONObject;
import com.yifushidai.dtoAndvo.SaveDetailVo;
import com.yifushidai.entity.*;
import com.yifushidai.mapper.*;
import com.yifushidai.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;

@Service
public class PowerService {
    @Autowired
    private SaveETEntityMapper saveETEntityMapper;
    @Autowired
    private PowerEntityMapper powerEntityMapper;
    @Autowired
    private ApiUniqueMacMapper apiUniqueMacMapper;
    @Autowired
    private SaveETEntityMapper saveEMapper;
    @Autowired
    private WeeksDetailEntityMapper weeksMapper;
    @Autowired
    private MonthsDetailEntityMapper monthsMapper;
    @Autowired
    private QuartersDetailEntityMapper quartersMapper;
    @Autowired
    private YearsDetailEntityMapper yearsMapper;
    @Autowired
    private OptDeviceLogMapper optDeviceLogMapper;
    @Autowired
    private TokenEntityMapper tokenEntityMapper;

    public R details(int qtype, Query query) {
        List<SaveDetailVo> resultlist = new ArrayList<>();
        int total = 0;
        //遍历计算 百分比
        Double totalSave = 0.00;
        if (qtype == 1) {//周
            List<WeeksDetailEntity> weeksDetailEntities = weeksMapper.queryByMac(query);
            for (WeeksDetailEntity week : weeksDetailEntities) {
                totalSave = totalSave + week.getSavetimes();
            }
            for (WeeksDetailEntity week : weeksDetailEntities) {
                Double persent = (week.getSavetimes() / totalSave);
                SaveDetailVo saveDetailVo = new SaveDetailVo(week, persent);
                resultlist.add(saveDetailVo);
            }
            total = weeksMapper.queryByMacTotal(query);
        }
        if (qtype == 2) {//月
            List<MonthsDetailEntity> monthsDetailEntities = monthsMapper.queryByMac(query);
            for (MonthsDetailEntity month : monthsDetailEntities) {
                totalSave = totalSave + month.getSavetimes();
            }
            for (MonthsDetailEntity month : monthsDetailEntities) {
                Double persent = (month.getSavetimes() / totalSave);
                SaveDetailVo saveDetailVo = new SaveDetailVo(month, persent);
                resultlist.add(saveDetailVo);
            }
            total = monthsMapper.queryByMacTotal(query);
        }
        if (qtype == 3) {//季度
            List<QuartersDetailEntity> quartersDetailEntities = quartersMapper.queryByMac(query);
            for (QuartersDetailEntity quarter : quartersDetailEntities) {
                totalSave = totalSave + quarter.getSavetimes();
            }
            for (QuartersDetailEntity quarter : quartersDetailEntities) {
                Double persent = (quarter.getSavetimes() / totalSave);
                SaveDetailVo saveDetailVo = new SaveDetailVo(quarter, persent);
                resultlist.add(saveDetailVo);
            }
            total = quartersMapper.queryByMacTotal(query);
        }
        if (qtype == 4) {//年
            List<YearsDetailEntity> yearsDetailEntities = yearsMapper.queryByMac(query);
            for (YearsDetailEntity years : yearsDetailEntities) {
                totalSave = totalSave + years.getSavetimes();
            }
            for (YearsDetailEntity years : yearsDetailEntities) {
                Double persent = (years.getSavetimes() / totalSave);
                SaveDetailVo saveDetailVo = new SaveDetailVo(years, persent);
                resultlist.add(saveDetailVo);
            }
            total = yearsMapper.queryByMacTotal(query);
        }
        return R.ok().put(new PageUtils(resultlist, total, query.getLimit(), query.getPage()));
    }

    private LinkedHashMap<String, List<PowerEntity>> queryYearList(List<PowerEntity> list) {
        LinkedHashMap<String, List<PowerEntity>> map = new LinkedHashMap<>();
        for (PowerEntity li : list) {
            //将需要归类的属性与map中的key进行比较，如果map中有该key则添加bean如果没有则新增key
            if (map.containsKey(li.getYear() + "年")) {
                //取出map中key对应的list并将遍历出的bean放入该key对应的list中
                ArrayList<PowerEntity> templist = (ArrayList<PowerEntity>) map.get(li.getYear() + "年");
                templist.add(li);
            } else {
                //创建新的list
                ArrayList<PowerEntity> temlist = new ArrayList<PowerEntity>();
                temlist.add(li);
                map.put(li.getYear() + "年", temlist);
            }
        }
        return map;
    }

    private LinkedHashMap<String, List<PowerEntity>> queryQuarterList(List<PowerEntity> list) {
        LinkedHashMap<String, List<PowerEntity>> map = new LinkedHashMap<>();
        for (PowerEntity li : list) {
            //将需要归类的属性与map中的key进行比较，如果map中有该key则添加bean如果没有则新增key
            if (map.containsKey(li.getYear() + "年第" + li.getQuarter() + "季度")) {
                //取出map中key对应的list并将遍历出的bean放入该key对应的list中
                ArrayList<PowerEntity> templist = (ArrayList<PowerEntity>) map.get(li.getYear() + "年第" + li.getQuarter() + "季度");
                templist.add(li);
            } else {
                //创建新的list
                ArrayList<PowerEntity> temlist = new ArrayList<PowerEntity>();
                temlist.add(li);
                map.put(li.getYear() + "年第" + li.getQuarter() + "季度", temlist);
            }
        }
        return map;
    }

    private LinkedHashMap<String, List<PowerEntity>> queryMonthList(List<PowerEntity> list) {
        LinkedHashMap<String, List<PowerEntity>> map = new LinkedHashMap<>();
        for (PowerEntity li : list) {
            //将需要归类的属性与map中的key进行比较，如果map中有该key则添加bean如果没有则新增key
            if (map.containsKey(li.getYear() + "年" + li.getMonth() + "月")) {
                //取出map中key对应的list并将遍历出的bean放入该key对应的list中
                ArrayList<PowerEntity> templist = (ArrayList<PowerEntity>) map.get(li.getYear() + "年" + li.getMonth() + "月");
                templist.add(li);
            } else {
                //创建新的list
                ArrayList<PowerEntity> temlist = new ArrayList<PowerEntity>();
                temlist.add(li);
                map.put(li.getYear() + "年" + li.getMonth() + "月", temlist);
            }
        }
        return map;
    }

    private LinkedHashMap<String, List<PowerEntity>> queryWeekList(List<PowerEntity> list) {
        LinkedHashMap<String, List<PowerEntity>> map = new LinkedHashMap<>();
        for (PowerEntity li : list) {
            //将需要归类的属性与map中的key进行比较，如果map中有该key则添加bean如果没有则新增key
            if (map.containsKey(li.getYear() + "年第" + li.getWeek() + "周")) {
                //取出map中key对应的list并将遍历出的bean放入该key对应的list中
                ArrayList<PowerEntity> templist = (ArrayList<PowerEntity>) map.get(li.getYear() + "年第" + li.getWeek() + "周");
                templist.add(li);
            } else {
                //创建新的list
                ArrayList<PowerEntity> temlist = new ArrayList<PowerEntity>();
                temlist.add(li);
                map.put(li.getYear() + "年第" + li.getWeek() + "周", temlist);
            }
        }
        return map;
    }

    public R control(int qtype, Query query) throws ParseException {
        List<JSONObject> resultlist = new LinkedList<JSONObject>();
        int total = 0;
        if (qtype == 0) {//当天
            List<PowerEntity> todayList = powerEntityMapper.queryTodayByMac(query);
            if (!todayList.isEmpty()) {
                total = powerEntityMapper.queryTodayByMacTotal(query);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("title", DateUtils.getCurrent());
                jsonObject.put("details", todayList);
                resultlist.add(jsonObject);
            }
        } else {
            List<PowerEntity> totalList = powerEntityMapper.queryAllByMac(query);
            if (!totalList.isEmpty()) {
                total = powerEntityMapper.queryAllByMacTotal(query);
                Map<String, List<PowerEntity>> resultMap = new LinkedHashMap<String, List<PowerEntity>>();
                if (qtype == 1) {//周
                    resultMap = queryWeekList(totalList);
                }
                if (qtype == 2) {//月
                    resultMap = queryMonthList(totalList);
                }
                if (qtype == 3) {//季度
                    resultMap = queryQuarterList(totalList);
                }
                if (qtype == 4) {//年
                    resultMap = queryYearList(totalList);
                }
                for (Map.Entry<String, List<PowerEntity>> entry : resultMap.entrySet()) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("title", entry.getKey());
                    jsonObject.put("details", entry.getValue());
                    resultlist.add(jsonObject);
                }
            }
        }
        return R.ok().put(new PageUtils(resultlist, total, query.getLimit(), query.getPage()));
    }

    public void savePower(String saveType, String body, ApiUniqueMac one, String addressSocket) throws ParseException {
        Date curTime = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(curTime);
        String curYears = String.valueOf(c.get(Calendar.YEAR));
        int month = c.get(Calendar.MONTH) + 1;
        String curMonths = String.valueOf(c.get(Calendar.MONTH) + 1);
        String curWeeks = String.valueOf(c.get(Calendar.WEEK_OF_YEAR));
        String curQuarters;
        if (month >= 1 && month <= 3) {
            curQuarters = "1";
        } else if (month >= 4 && month <= 6) {
            curQuarters = "2";
        } else if (month >= 7 && month <= 9) {
            curQuarters = "3";
        } else {
            curQuarters = "4";
        }

        StringBuilder param = new StringBuilder();
        param.append("老板！").append(one.getAlias()).append("房间于").append(DateUtils.getCurrent2());
        if ("of".equalsIgnoreCase(body)) {
            param.append(saveType).append("断电，设备进入节电模式。");
            powerEntityMapper.insertSelective(PowerEntity.builder()
                    .mac(one.getMac())
                    .typ(CustomPackUtils.OFF_LINE)
                    .saveType(saveType)
                    .year(curYears)
                    .quarter(curQuarters)
                    .month(curMonths)
                    .week(curWeeks)
                    .build());
        } else if ("on".equalsIgnoreCase(body)) {
            param.append(saveType).append("通电。");
            double saveHour = 0.0;
            List<PowerEntity> lastOne = powerEntityMapper.queryLatestByMac(one.getMac());
            if (!lastOne.isEmpty() && CustomPackUtils.OFF_LINE == lastOne.get(0).getTyp()) {
                saveHour = (double) (c.getTimeInMillis() - lastOne.get(0).getPowerTime().getTime()) / 3600000;
                if (24.0 < saveHour) {
                    saveHour = 0.0;
                } else {
                    one.setSavetotal(one.getSavetotal() + saveHour);
                    one.setSavetoday(one.getSavetoday() + saveHour);
                    apiUniqueMacMapper.updateByPrimaryKeySelective(one);

                    //省电详情计算
                    saveEMapper.insertSelective(SaveETEntity.builder().mac(one.getMac()).saveetime(saveHour).build());

                    WeeksDetailEntity weekDetail = weeksMapper.queryCur(one.getMac(), curWeeks, curYears);
                    MonthsDetailEntity monthDetail = monthsMapper.queryCur(one.getMac(), curMonths, curYears);
                    QuartersDetailEntity quarterDetail = quartersMapper.queryCur(one.getMac(), curYears, curQuarters);
                    YearsDetailEntity yearDetail = yearsMapper.queryCur(one.getMac(), curYears);
                    if (weekDetail == null) {
                        weeksMapper.insertSelective(WeeksDetailEntity.builder().mac(one.getMac()).savetimes(saveHour).years(curYears).weeks(curWeeks).build());
                    } else {
                        weekDetail.setSavetimes(weekDetail.getSavetimes() + saveHour);
                        weeksMapper.updateByPrimaryKeySelective(weekDetail);
                    }
                    if (monthDetail == null) {
                        monthsMapper.insertSelective(MonthsDetailEntity.builder().mac(one.getMac()).savetimes(saveHour).years(curYears).months(curMonths).build());
                    } else {
                        monthDetail.setSavetimes(monthDetail.getSavetimes() + saveHour);
                        monthsMapper.updateByPrimaryKeySelective(monthDetail);
                    }
                    if (quarterDetail == null) {
                        quartersMapper.insertSelective(QuartersDetailEntity.builder().mac(one.getMac()).savetimes(saveHour).years(curYears).quarters(curQuarters).months(curMonths).build());
                    } else {
                        quarterDetail.setSavetimes(quarterDetail.getSavetimes() + saveHour);
                        quartersMapper.updateByPrimaryKeySelective(quarterDetail);
                    }
                    if (yearDetail == null) {
                        yearsMapper.insertSelective(YearsDetailEntity.builder().mac(one.getMac()).savetimes(saveHour).years(curYears).build());
                    } else {
                        yearDetail.setSavetimes(yearDetail.getSavetimes() + saveHour);
                        yearsMapper.updateByPrimaryKeySelective(yearDetail);
                    }
                }
            }
            powerEntityMapper.insertSelective(PowerEntity.builder()
                    .mac(one.getMac())
                    .typ(CustomPackUtils.ON_LINE)
                    .saveType(saveType)
                    .saveHour(saveHour)
                    .year(curYears)
                    .quarter(curQuarters)
                    .month(curMonths)
                    .week(curWeeks)
                    .build());
        } else {
            return;
        }

        Set<String> mobileSet = new LinkedHashSet<>();
        mobileSet.add(one.getMobile());
        mobileSet.add(one.getMobile2());
        JPushUtils.shisuNotification(tokenEntityMapper, mobileSet, param.toString(), JPushUtils.LOG_POWER_STATUS_NOTIFICATION_TYPE);
        optDeviceLogMapper.insertSelective(OptDeviceLog.builder().addressSocket(addressSocket).mobile(one.getMobile()).uniqueMac(one.getMac()).powerMac(one.getPowerMac()).alias(one.getAddr() + one.getAlias()).optDesc(param.toString()).build());
    }

    public R sync() {
        List<ApiUniqueMac> list = apiUniqueMacMapper.selectAll();
        for (ApiUniqueMac one : list) {
            Double total = saveETEntityMapper.querySaveTotalByMac(one.getMac());
            Double today = saveETEntityMapper.querySaveTodayByMac(one.getMac());
            if (total == null) {
                total = 0.0;
            }
            if (today == null) {
                today = 0.0;
            }
            one.setSavetotal(total);
            one.setSavetoday(today);
            apiUniqueMacMapper.updateByPrimaryKeySelective(one);
        }
        return R.ok();
    }

   /* @Test
    public void test() throws ParseException {
        Calendar bef = Calendar.getInstance();
        Calendar aft = Calendar.getInstance();
        bef.setTime(DateUtils.toDate("2017-10-7 10:00:00"));
        aft.setTime(new Date());
        int days = aft.get(Calendar.DATE) - bef.get(Calendar.DATE);
        int weeks = aft.get(Calendar.WEEK_OF_YEAR) - bef.get(Calendar.WEEK_OF_YEAR);
        int months = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        int quarters = (aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH))/3;
        int years = aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR);

        System.out.println("days："+days);
        System.out.println("weeks："+weeks);
        System.out.println("months："+months);
        System.out.println("quarters："+quarters);
        System.out.println("years："+years);

        int daydiff = CalendarUtils.getDayDiff2("2016-10-7 10:00:00",DateUtils.getCurrent2());
        int daydiff2 = CalendarUtils.getDayDiff2("2016-10-7 10:00:00",DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        System.out.println("daydiff2："+daydiff2);
        System.out.println("daydiff："+daydiff);

    }
*/
   /* @Test
    public void test2(){
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        System.out.println(String.valueOf(c.get(Calendar.YEAR)) );
        System.out.println(String.valueOf( c.get(Calendar.WEEK_OF_YEAR)));
        System.out.println(String.valueOf( c.get(Calendar.MONTH))) ;//为 calendar 设置“月份（MONTH）”时需要 “-1”;通过 calendar 获取“月份（month）”时需要 “+1”


        String curWeeks = String.valueOf(c.getWeeksInWeekYear());
        String cur = String.valueOf(c.getWeekYear());
        System.out.println("weeks" + curWeeks);
        System.out.println("cur" + cur);
    }*/
/*
   @Test
   public void test(){
       Double persent = (50.00/88.00) + (50.00%88.00);
       System.out.println("persent1:"+(50.00/88.00));
       System.out.println("persent2:"+(50.00%88.00));
       System.out.println("persent3:"+(50.00%100));
   }*/
}
